package com.cys.dm.rest.service;

import com.alibaba.fastjson.JSONObject;
import com.cys.dm.client.user.DmLinkUserClient;
import com.cys.dm.entity.user.DmLinkUser;
import com.cys.dm.entity.user.DmUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;

/**
 * @author blue_t
 * @date 2020-12-23 15:52
 */
@Service
public class DmOrderLinkUserService {

    @Autowired
    private DmLinkUserClient dmLinkUserClient;
    @Autowired
    private RedisTemplate redisTemplate;

    public DmUser user(String token){
        // 获取redis中存储的用户id 并转换为json字符串
        String tokenStr = (String) JSONObject.toJSON(redisTemplate.opsForValue().get(token));
        // 将字符串转为json对象
        JSONObject tokenJs = JSONObject.parseObject(tokenStr);
        // 将json对象转为DmUser对象
        DmUser dmUser = tokenJs.toJavaObject(DmUser.class);
        return dmUser;
    }

    /**
     * 根据用户ID获取常用联系人
     * @return
     */
    public List<DmLinkUser> ticketbuyerlist(Map<String,Map<String,Object>> map){
        String str = map.get("token").get("token").toString();
        DmUser dmUser = user(str);
        return dmLinkUserClient.findAllByUserId(dmUser.getId());
    }

    /**
     * 根据身份证号查询常用联系人是否存在
     * @param map
     * @return
     */
    public String queryLinkUserByIdCard(Map<String,Long> map){
        Long idCard = map.get("idCard");
        DmLinkUser dmLinkUser = dmLinkUserClient.queryLinkUserByIdCard(idCard);
        if (dmLinkUser==null){
            return "购票人不存在";
        }else {
            return "购票人已存在";
        }
    }

    /**
     * 添加常用联系人
     * @param map
     * @return
     */
    public Integer addLinkUser(Map<String,Object> map){
        String str = map.get("userId").toString();
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userId = jsonObject.getString("userId");

        DmLinkUser dmLinkUser = new DmLinkUser();
        dmLinkUser.setUserId(Long.parseLong(userId));
        dmLinkUser.setName(map.get("name").toString());
        dmLinkUser.setIdCard(map.get("idCard").toString());
        dmLinkUser.setCardType(Long.parseLong(map.get("cardType").toString()));
        return dmLinkUserClient.addLinkUser(dmLinkUser);
    }

}
